<?php

declare(strict_types=1);

namespace App\Controller;

use App\Constants\ErrorCode;
use App\Service\FlyShopCashOrderService;
use App\Service\PayService;
use Psr\Http\Message\ResponseInterface;
use Hyperf\Di\Annotation\Inject;

/**
 * 商家保证金订单管理
 * Class ShopCashController
 * @package App\Controller
 */
class ShopCashController extends AbstractController
{
    /**
     * @Inject
     * @var FlyShopCashOrderService
     */
    private $cashOrder;

    /**
     * @Inject
     * @var PayService
     */
    private $payService;

    /**
     * 登陆商家用户ID
     * @return int
     */
    public function get_user_id(): int
    {
        return (int)$this->getAdminId();
    }

    /**
     * 创建保证金订单
     * @return ResponseInterface
     */
    public function createOrder(): ResponseInterface
    {
        $user_id = (int)$this->getAdminId();
        if (empty($user_id)) {
            return $this->jsonResponse->error(ErrorCode::NORMAL_ERROR, '未登录请先登录');
        }
        $result = $this->cashOrder->createCashOrder($user_id);
        if (empty($result['res'])) {
            return $this->jsonResponse->error(ErrorCode::NORMAL_ERROR, $result['msg']);
        }
        return $this->jsonResponse->success(['cash_order_sn' => $result['cash_order_sn']], '操作成功');
    }

    /**
     * 保证金订单支付
     * @return ResponseInterface
     */
    public function pay()
    {
        $user_id = $this->get_user_id();
        if (!$user_id) {
            return $this->jsonResponse->error(ErrorCode::NORMAL_ERROR, '未登录请先登录');
        }
        $params = $this->request->all();
        $pay_service = $this->payService;
        // 支付参数验证
        $pay_v = $pay_service->payVerify($params);
        if (!$pay_v['res']) {
            return $this->jsonResponse->error(ErrorCode::NORMAL_ERROR, $pay_v['msg']);
        }
        $pay_res = $pay_service->submit($pay_v['data']);
        return $this->jsonResponse->success($pay_res);
    }
}